'use strict';

const BaseService = require('./base');
const modelName = 'TaskRecord'
function createOrderNumber() {
    // 生成订单号 12位
    return 'R' + new Date().getTime() + Math.floor(Math.random() * 1000);
}
class RouterService extends BaseService {
    constructor(ctx) {
        super(ctx, modelName);
    }
    async findOne(id) {
        return await this.ctx.model[this.modelName].findOne({
            where: {
                id,
            },
            include: [
                {
                    model: this.ctx.model.User,
                    as: 'user'
                }
            ]
        });
    }
    async create(data) {
        return this.ctx.model[this.modelName].create({
            ...data,
            task_record_no: createOrderNumber()
        });
    }
    // 接单
    async accept(data) {
        const { ctx } = this;
        const { task_id, user_id } = data;
        // 用户
        const user = await ctx.model.User.findOne({
            where: {
                id: user_id,
                status: 1,
            }
        });
        if (!user) {
            throw new Error('用户不存在');
        }
        // 任务
        const task = await ctx.model.Task.findOne({
            where: {
                id: task_id
            }
        });
        if (!task) {
            throw new Error('任务不存在');
        }
        // 减库存
        if (task.count < 1) {
            throw new Error('库存不足');
        }
        await ctx.service.task.update({
            id: task_id,
            count: task.count - 1
        }, {
            where: {
                id: task_id
            }
        })
        // 创建任务
        return this.create(data);
    }

    async findByValues(values) {
        return this.ctx.model[this.modelName].findOne({
            where: values
        });
    }
}


module.exports = RouterService;
